package com.picket.dao;

import java.util.Collection;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.springframework.orm.jdo.support.JdoDaoSupport;
import org.springframework.stereotype.Repository;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.picket.domain.Event;
 
@Repository
public class EventDao extends JdoDaoSupport implements IEventDao {
 

  
 @Override
 public Key create(final Event event) {
  getJdoTemplate().makePersistent(event);
  return event.getKey();
 }
 
 @Override
 public Collection<Event> getAllEvents() {
 
  final PersistenceManager pm = getPersistenceManager();
   
  try {
 
   final Query query = pm.newQuery(Event.class);
   //query.setOrdering("date descending");
    
   @SuppressWarnings("unchecked")
   final Collection<Event> events =
    (Collection<Event>) query.execute();
    
   return pm.detachCopyAll((Collection<Event>)events);
  }
   
  finally {
   releasePersistenceManager(pm);
  }
 
 }
 
 
 @Override
 public Event getEvent(long id) {
 
  final PersistenceManager pm = getPersistenceManager();
   
  try {
	  
	  Key k = KeyFactory.createKey(Event.class.getSimpleName(), id);
      return pm.getObjectById(Event.class, k);
  }
   
  finally {
   releasePersistenceManager(pm);
  }
 
 }
}